<template>
  <view class="component-baidu-echarts">
    <!-- #ifdef APP-PLUS || H5 -->
    <view class="echarts"
          :id="echartsID"
          :change:id="ModuleInstance.reciveID"
          :option="option"
          :change:option="ModuleInstance.setOption"
          :style="{height:`${height}rpx`}"></view>
    <!-- #endif -->

    <!-- #ifndef APP-PLUS || H5 -->
    <view>非 APP、H5 环境不支持renderjs模式"</view>
    <!-- #endif -->
  </view>
</template>

<script>
export default {
  props: {
    height: {
      type: Number,
      default: 520,
      required: false,
    },
    option: {
      type: Object,
      default: () => {},
      required: false,
    },
  },
  data() {
    return {
      echartsID: `echartsID-${Date.now()}-${parseInt(Math.random() * 1e8)}`, //生成唯一的ID
    };
  },
  /*注意：uniapp子组件是没onLoad()和onShow()生命周期，只有页面组件才有 */
  mounted() {},
  methods: {},
};
</script>
<script module="ModuleInstance" lang="renderjs">
//let myChart;深坑：同一个页面同时引入该组件，myChart变量会被替换成最后一个实例，所以使用this.myChart保存实例
export default {
    data() {
        return {
            echartsID: '',//接收唯一的ID
            myChart:null,
        };
    },
    mounted(){
        if (typeof window.echarts === 'function') {
            // 观测更新的数据在 view 层可以直接访问到
            this.initEchart();
        } else {
            // 动态引入较大类库避免影响页面展示
            const script = document.createElement('script');
            // view 层的页面运行在 www 根目录，其相对路径相对于 www 计算
            script.src = 'static/js/echarts.min.js';
            //script标签的onload事件都是在外部js文件被加载完成并执行完成后才被触发的
            script.onload = () => {
                this.initEchart();
            }
            document.head.appendChild(script); 
        }
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.myChart.resize)
        this.myChart.dispose()
    },
    methods: {
        initEchart(){
            this.myChart = echarts.init(document.getElementById(this.echartsID));
            this.myChart.setOption(this.option || {});
            window.addEventListener('resize', this.myChart.resize);
        },
        reciveID(id) {
            this.echartsID = id;
        },
        setOption(newValue, oldValue, ownerInstance, instance){
            if(this.myChart){
                this.myChart.clear();//清空画布
                this.myChart.setOption(newValue || {});
            }
        }
    },
};
</script>
<style lang="scss">
.component-baidu-echarts {
  .echarts {
    width: 100%;
    min-height: 50px;
  }
}
</style>